--叶佳豪 201841052073
--日计数可变进制 BCD码加法计数器
--***************************************
LIBRARY IEEE;
USE IEEE.STD_LOGIC_1164.ALL;
USE IEEE.STD_LOGIC_ARITH.ALL;
USE IEEE.STD_LOGIC_UNSIGNED.ALL;
--*************************************************
ENTITY COUNT_DAY IS
    PORT(
			CLK,CLR		:IN STD_LOGIC;
			ISLeapYear	:IN STD_LOGIC;							--当前是不是闰年 1为闰年
			MONTH		:IN STD_LOGIC_vector(7 downto 0);		--4*2一共8位当前月
			Q 			:OUT STD_LOGIC_vector(7 downto 0);
			TCN			:OUT STD_LOGIC
		);
END COUNT_DAY;
--**************************************************
ARCHITECTURE RUN OF COUNT_DAY IS
SIGNAL COUNT_T : std_logic_vector(7 downto 0):="00000001";
signal CountType :integer := 1;				--当前的计数模式 默认值给1解决上电一瞬间的异常
BEGIN
P_MONTHSET:PROCESS(CLK,ISLeapYear,MONTH)
	BEGIN
		IF CLK'EVENT AND CLK = '1' THEN
			CASE MONTH IS
				WHEN "00000001" =>CountType<=1;--1
				WHEN "00000010" =>IF ISLeapYear = '1' THEN CountType<=3;ELSE CountType<=2;END IF;
				WHEN "00000011" =>CountType<=1;--3
				WHEN "00000100" =>CountType<=0;--4
				WHEN "00000101" =>CountType<=1;--5
				WHEN "00000110" =>CountType<=0;--6
				WHEN "00000111" =>CountType<=1;--7
				WHEN "00001000" =>CountType<=1;--8
				WHEN "00001001" =>CountType<=0;--9
				WHEN "00010000" =>CountType<=1;--10
				WHEN "00010001" =>CountType<=0;--11
				WHEN "00010010" =>CountType<=1;--12
				WHEN OTHERS=>NULL;--其他情况不可能
			END CASE;
			
		END IF;		
	END PROCESS;
P_DAYCOUNT:PROCESS(CLK,CLR)
	BEGIN
		IF CLR = '0' THEN COUNT_T <= "00000001";--每个月从1开始计数
		ELSIF CLK'EVENT AND CLK = '1' THEN
			TCN<='0';
			IF COUNT_T >= "00110000" AND CountType=0 THEN 	COUNT_T <= "00000001";TCN<='1';			--30进制
			ELSIF COUNT_T >= "00110001" AND CountType=1 THEN 	COUNT_T <= "00000001";TCN<='1';		--31进制
			ELSIF COUNT_T >= "00101001" AND CountType=2 THEN 	COUNT_T <= "00000001";TCN<='1';		--29进制
			ELSIF COUNT_T >= "00101000" AND CountType=3 THEN 	COUNT_T <= "00000001";TCN<='1';		--28进制
			ELSIF COUNT_T(3 downto 0) >= "1001" THEN						--十位进位
				COUNT_T(3 downto 0) <= "0000";
				COUNT_T(7 downto 4) <= COUNT_T(7 downto 4) + 1;
			ELSE COUNT_T <= COUNT_T + 1;							--个位进位
			END IF;
		END IF;
		Q <= COUNT_T;
	END PROCESS;

END RUN;